//
//  settingViewController.m
//  lmq
//
//  Created by 千翼网络科技 on 2017/1/23.
//  Copyright © 2017年 yuanxin. All rights reserved.
//

#import "settingViewController.h"
#import "settingTableViewCell.h"
#import "personViewController.h"
#import "addressViewController.h"
#import "aboutusViewController.h"
#import "loginViewController.h"
#import "Masonry.h"

@interface settingViewController ()

@property (nonatomic, strong) UITableView *settingTableView;
@property (nonatomic, strong) UILabel *cacheLabel;
@end

@implementation settingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setTitle:@"设置"];

    settingArr=[[NSMutableArray alloc]init];
    
    NSMutableDictionary *dict1=[[NSMutableDictionary alloc]init];
    [dict1 setObject:@"个人信息" forKey:@"name"];
    
    NSMutableDictionary *dict2=[[NSMutableDictionary alloc]init];
    [dict2 setObject:@"收货地址管理" forKey:@"name"];
    
//    NSMutableDictionary *dict3=[[NSMutableDictionary alloc]init];
//    [dict3 setObject:@"意见与反馈" forKey:@"name"];
    
    NSMutableDictionary *dict4=[[NSMutableDictionary alloc]init];
    [dict4 setObject:@"清除缓存" forKey:@"name"];
    
    NSMutableDictionary *dict5=[[NSMutableDictionary alloc]init];
    [dict5 setObject:@"关于我们" forKey:@"name"];
    
//    NSMutableDictionary *dict6=[[NSMutableDictionary alloc]init];
//    [dict6 setObject:@"给我评分" forKey:@"name"];
    
    [settingArr addObject:dict1];
    [settingArr addObject:dict2];
//    [settingArr addObject:dict3];
    [settingArr addObject:dict4];
    [settingArr addObject:dict5];
//    [settingArr addObject:dict6];
    
    UIButton *quitButton=[[UIButton alloc]initWithFrame:CGRectMake(0, DEF_SCREEN_HEIGHT-64-(50), DEF_SCREEN_WIDTH, (50))];
    quitButton.backgroundColor=[UIColor whiteColor];
    [quitButton setTitle:@"退出当前账号" forState:UIControlStateNormal];
    [quitButton addTarget:self action:@selector(quitButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [quitButton setTitleColor:[ZJCModel colorWithString:@"ff2222"] forState:UIControlStateNormal];
    [self.view addSubview:quitButton];
    
    self.settingTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64-(50)) style:UITableViewStylePlain];
    self.settingTableView.backgroundColor=[ZJCModel colorWithString:@"f2f2f2"];
    self.settingTableView.separatorStyle=UITableViewCellSelectionStyleNone;
    self.settingTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.settingTableView.delegate=self;
    self.settingTableView.dataSource=self;
    [self.view addSubview:self.settingTableView];
}

-(void)quitButtonClick{
    
    loginViewController *VC = [[loginViewController alloc] init];
    [self.navigationController pushViewController:VC animated:YES];
    NSLog(@"退出当前账号");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

#pragma mark -----UITableViewDataSource-----

//返回分区数(默认为1)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//返回每一行的cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4;
}

#pragma mark -----UITableViewDelegate-----
//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return (45);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    settingTableViewCell *cell=(settingTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"settingTableViewCell"];
    if (cell == nil) {
        cell=[[settingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"settingTableViewCell"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    
    cell.titLable.text=[settingArr[indexPath.row] objectForKey:@"name"];
    
    
    if (indexPath.row == 2) {
        self.cacheLabel = [[UILabel alloc] init];
        self.cacheLabel.textAlignment = NSTextAlignmentRight;
        self.cacheLabel.font = [UIFont systemFontOfSize:13];
        self.cacheLabel.text = [NSString stringWithFormat : @"%.2fM" , [self filePath]];
        [cell addSubview:self.cacheLabel];
        [self.cacheLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell).with.offset(10);
            make.right.equalTo(cell).with.offset(-40);
            make.bottom.equalTo(cell).with.offset(-10);
            make.width.offset(100);
        }];

        
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
  
    
    if(indexPath.row==0){
        personViewController *personVC=[[personViewController alloc]init];
        [self.navigationController pushViewController:personVC animated:YES];
    }else if (indexPath.row==1){
        addressViewController*addressVC=[[addressViewController alloc]init];
        [self.navigationController pushViewController:addressVC animated:YES];
        
    }
    else if (indexPath.row==2){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否清除缓存" preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
            [self clearFile];
            
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        [alert addAction:action];
        [alert addAction:cancel];
        [self showDetailViewController:alert sender:nil];
        //清除缓存
        

        
    }else if (indexPath.row==3){
        aboutusViewController*aboutusVC=[[aboutusViewController alloc]init];
        [self.navigationController pushViewController:aboutusVC animated:YES];
    }
    
}
//首先计算单个文件的大小

- (long long)fileSizeAtPath:(NSString *)filePath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error : nil] fileSize];
        
    }
    
    return 0 ;
    
}

//遍历文件夹获得文件夹大小，返回多少M

- (float)folderSizeAtPath:(NSString *)folderPath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]) return 0 ;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator];
    
    NSString * fileName;
    
    long long folderSize = 0 ;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
        
    }
    
    return folderSize/( 1024.0 * 1024.0 );
    
}

// 显示缓存大小

- (float)filePath

{
    
    NSString * cachPath = [NSSearchPathForDirectoriesInDomains( NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    
    return [self folderSizeAtPath:cachPath];
    
}

// 清理缓存

- (void)clearFile

{
    
    NSString * cachPath = [NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    
    NSArray * files = [[NSFileManager defaultManager] subpathsAtPath :cachPath];
    
    NSLog (@"cachpath = %@" , cachPath);
    
    for (NSString *p in files) {
        
        NSError *error = nil ;
        
        NSString *path = [cachPath stringByAppendingPathComponent:p];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath :path]){
            
            [[NSFileManager defaultManager] removeItemAtPath :path error :&error];
            
        }
        
    }
    
    [self performSelectorOnMainThread:@selector(clearCachSuccess) withObject:nil waitUntilDone:YES];
    
}

- (void)clearCachSuccess

{
    
    NSLog(@"清理成功");
    
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message: @"缓存清理完毕" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    
    [alertView show];
    self.cacheLabel.text = nil;
    
    [self.settingTableView reloadData];//清理完之后重新导入数据
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
